#pragma once
#include <iostream>
#include <cstring>
#include <sys/epoll.h>
#include "logMessage.hpp"
const int size = 128;
const int default_num = -1;
class Epoller
{
public:
    Epoller() : _epfd(default_num)
    {
    }
    ~Epoller()
    {
        if (_epfd != default_num)
            close(_epfd);
    }
    void Create()
    {
        _epfd = epoll_create(size);
        if (_epfd < 0)
        {
            logMessage(ERROR, "create error :%s", strerror(errno));
            exit(1);
        }
    }
    void Add_Event(int sock, uint32_t event)
    {
        if (_epfd < 0)
        {
            logMessage(ERROR, "epoll模型还没创建");
            exit(1);
        }
        struct epoll_event retev;
        retev.data.fd = sock;
        retev.events = event;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sock, &retev);
        if (n == 0)
            logMessage(NORMAL, "add listen fd success");
    }
    bool Control(int sock, uint32_t event, int action)
    {
        int n = 0;
        if (action == EPOLL_CTL_MOD)
        {
            struct epoll_event ev;
            ev.data.fd = sock;
            ev.events = event;
            epoll_ctl(_epfd, action, sock,&ev);
        }
        else if(action == EPOLL_CTL_DEL)
        {
            epoll_ctl(_epfd,action,sock,nullptr);
        }
        else 
        n = -1;
        return n==0;
    }
    int Wait(struct epoll_event *rev, int size, int timeout)
    {
        int n = epoll_wait(_epfd, rev, size, timeout);
        return n;
    }

public:
    // 存放epoll模型
    int _epfd;
    // struct epoll_event *_ev;
};